package com.zyg.mq;

import com.alibaba.fastjson.JSON;
import com.zyg.config.RabbitMQConfig;
import com.zyg.pojo.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Slf4j
@Component
public class ZygMsgSender implements RabbitTemplate.ConfirmCallback {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private ZygMsgSender(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if(ack){
            // log.info("回调生产者：{}" , correlationData.getId() );
        } else {
            //失败则进行具体的后续操作:重试 或者补偿等手段
            log.error("异常：{}" , cause );
        }
    }

    /**
     * 消息交换机发送
     * @param
     */
    public void send(String content,String topicName) {
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        log.info("String - message:{}",content);
        this.rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_ZYG_DATA_MSG, topicName, content, correlationData);
    }

    public void sendUser(SysUser user, String topicName) {
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        log.info("Object - message:{}", JSON.toJSONString(user));
        this.rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_ZYG_DATA_MSG, topicName, user, correlationData);
    }
}
